package eai.tp2.lpco.web.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import eai.tp2.lpco.credentials.auth.IAuthentication;
import eai.tp2.lpco.web.beans.ErrorList;

/**
 * Servlet implementation class Logout
 */
public class Logout extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Logout() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		IAuthentication auth = null;
		InitialContext ctx = null;
		try {
			ctx = new InitialContext();
			auth = (IAuthentication) ctx.lookup("AuthenticationBean/remote");
			if(auth.logout()) {
				session.invalidate();
				response.sendRedirect("DatabaseCatalog?do=list");
			}
		} catch (NamingException e) {			
			String error;
			error = "Error while lookup for AuthenticationBean:\n"+e.getMessage();
			List<String> errors = new ArrayList<String>();
			errors.add(error);
			ErrorList list = new ErrorList();
			list.setErrorList(errors);		
			request.setAttribute("list", list);
			RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
			rd.forward(request, response);	
		}				
	}

}
